package com.laf.manage.listener;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.laf.common.constant.CacheConstants;
import com.laf.common.constant.MQConstant;
import com.laf.common.core.redis.RedisCache;
import com.laf.common.exception.ServiceException;
import com.laf.manage.domain.doc.DynamicDoc;
import com.laf.manage.domain.dto.AddDynamicDocMsg;
import com.laf.manage.domain.po.Comments;
import com.laf.manage.domain.po.Dynamic;
import com.laf.manage.domain.po.Store;
import com.laf.manage.enums.ContentTypeEnum;
import com.laf.manage.mapper.es.DynamicEsMapper;
import com.laf.manage.service.ICommentsService;
import com.laf.manage.service.IDynamicService;
import com.laf.manage.service.IStoreService;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 内容监听器
 */
@Component
public class DynamicListener {

    @Autowired
    private DynamicEsMapper dynamicEsMapper;

    @Autowired
    private IDynamicService dynamicService;

    @Autowired
    private ICommentsService commentsService;

    @Autowired
    private IStoreService storeService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 新增 es 中 contentDoc
     *
     * @param msg id 动态id
     *            tagIds 标签ids
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstant.DYNAMIC_ADD_QUEUE, durable = "true", arguments = @Argument(name = "x-queue-mode", value = "lazy")),
            exchange = @Exchange(value = MQConstant.DYNAMIC_EXCHANGE),
            key = MQConstant.DYNAMIC_ADD_ROUTING_KEY
    ))
    public void addContentDoc(AddDynamicDocMsg msg) {
        Long id = msg.getId();
        // 1. 查询内容是否存在，做幂等处理
        DynamicDoc dynamicDoc = dynamicEsMapper.selectById(id);
        if (dynamicDoc != null) return;

        // 2. 查询 mysql 获取数据 ，如果数据不存在，直接丢弃消息即可
        Dynamic dbDynamic = dynamicService.getById(id);
        if (dbDynamic == null) return;

        // 3. 写入 es
        DynamicDoc doc = BeanUtil.copyProperties(dbDynamic, DynamicDoc.class);
        doc.setTagIds(msg.getTagIds());
        doc.setVerifyStatus(dbDynamic.getVerifyStatus().getCode());
        Integer result = dynamicEsMapper.insert(doc);
        if (result <= 0) throw new ServiceException(" DynamicListener.addContentDoc 写入es 失败 ，id: " + id);
    }


    /**
     * 删除 es 中 DynamicDoc
     */

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(
                    value = MQConstant.DYNAMIC_DELETE_QUEUE,
                    durable = "true",
                    arguments = @Argument(name = "x-queue-mode", value = "lazy")
            ),
            exchange = @Exchange(value = MQConstant.DYNAMIC_EXCHANGE),
            key = MQConstant.DYNAMIC_DELETE_ROUTING_KEY
    ))
    public void deleteDynamicDoc(List<Long> ids) {
        // 删除评论
        commentsService.remove(
                Wrappers.<Comments>lambdaQuery()
                        .in(Comments::getDynamicId, ids)
        );


        // 删除收藏
        storeService.remove(
                Wrappers.<Store>lambdaQuery()
                        .in(Store::getContentId, ids)
                        .eq(Store::getContentType, ContentTypeEnum.DYNAMIC)
        );

        // 删除 es
        dynamicEsMapper.deleteBatchIds(ids);


        // 删除缓存中的数据 、  浏览量 收藏量 评论数
        for (Long id : ids) {
            String idString = id.toString();
            redisCache.deleteCacheMapValue(CacheConstants.COMMENTS_PREFIX, idString);
            redisCache.deleteCacheMapValue(CacheConstants.STORE_PREFIX, idString);
            redisCache.deleteCacheMapValue(CacheConstants.HITS_PREFIX, idString);
        }



    }


}
